/*
 * GleonWebServiceSource.java
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package vegadataeditor.dataSources;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import vegadataeditor.VegaStreamContainer;

/**
 *
 * @author lawinslow
 */
public class GleonWebServiceSource implements IDataSource{

    private gleonwebservice.GleonData port;

    public GleonWebServiceSource(){
            gleonwebservice.GleonDataServiceService service = new gleonwebservice.GleonDataServiceService();
            port = service.getGleonDataPort();
    }



    public List<VegaStreamContainer> getAllStreams() throws SourceConnectionException {

        ArrayList<VegaStreamContainer> streams = new ArrayList<VegaStreamContainer>();

        try {
            java.util.List<gleonwebservice.VegaStreamContainer> result = port.getAllStreamMetadata();
            VegaStreamContainer tmp = null;
            for(gleonwebservice.VegaStreamContainer stream:result){
                if(stream == null)
                    continue;
                
                tmp = new VegaStreamContainer();

                if(stream.getEarliestDate() == null){
                    tmp.earliestDate = null;
                }else{
                    tmp.earliestDate = stream.getEarliestDate().toGregorianCalendar().getTime();
                }
                if(stream.getLatestDate()==null){
                    tmp.latestDate = null;
                }else{
                    tmp.latestDate = stream.getLatestDate().toGregorianCalendar().getTime();
                }
                

                tmp.AggMethod = stream.getAggMethod();
                tmp.AggSpanInSec = stream.getAggSpanInSec();
                tmp.method = stream.getMethod();
                tmp.offsetType = stream.getOffsetType();
                tmp.offsetValue = stream.getOffsetValue();
                tmp.site = stream.getSite();
                tmp.source = stream.getSource();
                tmp.streamID = stream.getStreamID();
                tmp.unit = stream.getUnit();
                tmp.variable = stream.getVariable();

                streams.add(tmp);
                
            }
            return streams;
        } catch (Exception ex) {
            throw new SourceConnectionException("Unable to connect to web service.",ex);
        }

    }

    public List<String> getSites() throws SourceConnectionException {

        try {
            java.util.List<java.lang.String> result = port.getSites();
            return result;
        } catch (Exception ex) {
           throw new SourceConnectionException("Unable to connect to web service.",ex);
        }


    }

    public List<String> getVariables() throws SourceConnectionException {

        try {
            java.util.List<java.lang.String> result = port.getVariables();
            return result;
        } catch (Exception ex) {
            throw new SourceConnectionException("Unable to connect to web service.",ex);
        }






    }

    public VegaStreamContainer getData(VegaStreamContainer request) throws SourceConnectionException {
        try {
            Calendar cal = GregorianCalendar.getInstance();

            XMLGregorianCalendar startCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
            XMLGregorianCalendar endCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();

            cal.setTime(request.startRetrieved);

            startCal.setYear(cal.get(Calendar.YEAR));
            startCal.setMonth(1+cal.get(Calendar.MONTH));
            startCal.setDay(cal.get(Calendar.DAY_OF_MONTH));
            startCal.setHour(cal.get(Calendar.HOUR_OF_DAY));
            startCal.setMinute(cal.get(Calendar.MINUTE));
            startCal.setSecond(cal.get(Calendar.SECOND));
            cal.setTime(request.endRetrieved);

            endCal.setYear(cal.get(Calendar.YEAR));
            endCal.setMonth(1+cal.get(Calendar.MONTH));
            endCal.setDay(cal.get(Calendar.DAY_OF_MONTH));
            endCal.setHour(cal.get(Calendar.HOUR_OF_DAY));
            endCal.setMinute(cal.get(Calendar.MINUTE));
            endCal.setSecond(cal.get(Calendar.SECOND));


            gleonwebservice.VegaStreamContainer result = port.getStreamDataCSV(startCal, endCal, request.streamID);
            // TODO process result here

            if(result.getCsv()==null || result.getCsv().length() == 0){
                request.hasNoValues = true;
            }else{
                request.hasNoValues = false;
            }

            try{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                request.values = new ArrayList<Double>();
                request.datetime = new ArrayList<Date>();

                for(String line:result.getCsv().split("\n")){
                    if(line.equalsIgnoreCase("")){
                        continue;
                    }
                    String[] splitLine = line.split(",");

                    request.datetime.add(format.parse(splitLine[0]));
                    request.values.add(Double.valueOf(splitLine[1]));

                }
            }catch(Exception e){
                e.printStackTrace();
                request.hasNoValues = true;
                request.values = null;
                request.datetime = null;
            }
            return request;

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new SourceConnectionException("Unable to connect to web service.",ex);
        }
    }
}
